import ast
import datetime
import logging

from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.views.generic.base import View

from system.models import Terminal, ApplyAccount
from utils.common.tools import query_params

logger = logging.getLogger(__name__)


@method_decorator(login_required, name='get')
class DeviceView(TemplateView):
    """设备视图"""

    template_name = 'system/device.html'


@method_decorator(login_required, name='get')
class DeviceListView(View):
    """设备列表页数据"""

    def get(self, request):
        ret = {'code': 0, 'msg': 'success', 'count': 0, 'data': []}
        user = request.user
        page = int(request.GET.get('page', 1))
        limit = int(request.GET.get('limit', 10))
        start, end = (page - 1) * limit, page * limit  # 计算要查询的数据数量

        # 过滤
        device_name = request.GET.get('device_name')  # 设备名称
        device_mac = request.GET.get('device_mac')  # 设备 Mac
        query_conditions = {'name__contains': device_name, 'mac_addr__contains': device_mac}
        conditions = query_params(query_conditions)

        route_mac = request.GET.get("mac_addr")  # 路由器mac地址

        print(conditions)

        # 查询
        if not conditions:
            # 从路由器跳转过来，过来绑定该路由器的设备
            if route_mac:
                device_obj = Terminal.objects.filter(route__mac_addr=route_mac)[start:end]
            else:
                device_obj = Terminal.get_device(user.id, start, end)  # 查询所有
        else:
            if route_mac:
                device_obj = Terminal.objects.filter(route__mac_addr=route_mac).filter(**conditions)[start: end]
            else:
                device_obj = Terminal.get_device_filter(user.id, conditions, start, end)  # 过滤查询

        # 获取设备列表
        device_list = Terminal.get_device_list(device_obj)
        print('device_obj', device_obj)

        # 已启用通道的设备，查询其公网 IP

        # 查询设备状态

        # print(device_list)
        #
        ret['count'] = Terminal.total_nums(request.user.id)
        ret['data'] = device_list

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class DeviceUpdateNameView(View):
    """修改设备名称"""

    def get(self, request):
        ret = {'code': 0, 'msg': '修改成功'}
        device_name = request.GET.get('name')
        device_mac_addr = request.GET.get('mac_addr')
        device_new_name = request.GET.get('new_name')

        # 是否为空
        if not device_new_name:
            ret['code'] = 10012
            ret['msg'] = '名字不能为空'
            return JsonResponse(ret)

        # 名字是否一致
        if device_name == device_new_name:
            ret['code'] = 10026
            ret['msg'] = '不能修改为相同名称'
            return JsonResponse(ret)

        # 名字长度
        if (len(device_new_name) >= 15) and (len(device_new_name) < 5):
            ret['code'] = 10027
            ret['msg'] = '名称长度 5-15个字符'
            return JsonResponse(ret)

        Terminal.objects.filter(mac_addr=device_mac_addr).update(**{'name': device_new_name})

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class DeviceAccount2LineView(View):
    """绑定设备：选择线路"""

    def get(self, request):
        mac_addr = request.GET.get('mac_addr')

        return render(request, 'system/device_account2line.html', {"mac_addr": mac_addr})

    def post(self, request):
        # {"广东省": ["广州", "佛山"], "北京": ["海淀", "廊坊"], "海南省": ["三亚", "海口"]}
        ret = {'code': 0, 'msg': '获取成功', 'data': None}
        user = request.user

        apply_line_dict = {}
        applys = ApplyAccount.objects.filter(user_id=user.id).filter(status=1)
        for apply in applys:
            apply_line_dict.update({
                apply.name: ast.literal_eval(apply.enable_lines)
            })

        print('apply_line_dict', apply_line_dict)

        ret['data'] = apply_line_dict

        return JsonResponse(ret)
